<template>
  <div class="table-box">
    <ProTable :tool-button="[]" ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <template #tableHeader>
        <el-button type="primary" :icon="Plus" plain @click="openDrawer('新增')">新增</el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" link @click="openDrawer('查看', scope.row)">详情</el-button>
        <el-button type="primary" v-if="userStore.userInfo.adminFlag" link @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { Admin } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import UserDrawer from "./components/UserDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Plus } from "@element-plus/icons-vue";
import { getUserList, deleteUser, addUser, getUserInfo } from "@/api/modules/user";
import { status } from "@/utils/dict";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
const proTable = ref<ProTableInstance>();

const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total,
    currentPage: data.current,
    pageSize: data.size
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  console.log("params", params);

  return getUserList(newParams);
};

const columns = reactive<ColumnProps<Admin>[]>([
  {
    prop: "username",
    label: "账号",
    search: { el: "input" },
    minWidth: 130
  },
  {
    prop: "realName",
    label: "姓名",
    search: { el: "input" },
    minWidth: 130
  },
  {
    prop: "department",
    label: "部门",
    minWidth: 100,
    search: { el: "input" }
  },
  {
    prop: "adminFlag",
    label: "是否管理员",
    minWidth: 100,
    enum: status
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 120 }
]);

const deleteAccount = async (params: Admin) => {
  await useHandleData(deleteUser, params.userId!, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};

const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = async (title: string, row: Partial<Admin> = {}) => {
  console.log("row.userId", row);
  let userInfo = {};
  if (title === "查看") {
    userInfo = await getUserInfo(row.userId!);
  }
  const params = {
    title,
    isView: title === "查看",
    row: { ...row, ...userInfo },
    api: title === "新增" ? addUser : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
